﻿layui.config({
    base: '/lib/layui/extend/'
}).extend({
    treeGrid: 'treeGrid'
}).use(['form', 'layer', 'laypage', 'treeGrid', 'jquery'], function () {
    var form = layui.form,
        $ = layui.jquery,
        player = parent.layer || layui.layer,
        treeGrid = layui.treeGrid; //很重要
    var authorityMenusListLogic = {
        //初始化
        init: function () {

            self = this;

            this.Parameters = {
                ac: new AsyncCaller(),    //异步方法管理
                systemTypeList: undefined,//系统类型
                functionypeList: undefined,//功能类型
                rowData: undefined,//选中行信息
                systemTypeListUrl: "/api/Authority/FunctionCfg/LoadSystemTypeList",
                functionTypeListUrl: "/api/Authority/FunctionCfg/LoadFunctionTypeList",
                listsUrl: "/api/Authority/FunctionCfg/LoadListInfo",
                moveSortUrl: "/api/Authority/FunctionCfg/MoveSort",
                removeUrl: "/api/Authority/FunctionCfg/Remove",
                forbiddenUrl: "/api/Authority/FunctionCfg/ForbidOrEnable",


                addUrl: "/Authority/Menus/Add",
                modifyUrl: "/Authority/Menus/Modify"
            };

            this.Parameters.ac
                .pushQueue(function () {
                    self.logicFunc.loadSystemTypeList(function () {
                        self.Parameters.ac.notifyQueueAsyncFuncComplate();
                    });
                })
                .pushQueue(function () {
                    self.logicFunc.loadFunctionTypeList(function () {
                        self.Parameters.ac.notifyQueueAsyncFuncComplate();
                    });
                })
                .pushQueue(function () {
                    self.initPage();
                    self.Parameters.ac.notifyQueueAsyncFuncComplate();
                })
                .pushQueue(this.bindEvent)
                .exec();
        },
        //初始化列表
        initPage: function () {

            var title =
                [
                    { type: 'radio' },
                    {
                        field: 'name', title: '菜单名称', width: '180',
                        templet: function (d) {
                            return '<a><i class="iconfont ' + d.icon_font + '" data-icon="' + d.icon_font + '" ></i><cite>' + d.name + '</cite></a>';
                        }
                    },
                    { field: 'icon_font', title: '标签icon', width: '200' },
                    { field: 'level', title: '级别', width: '80', align: "center" },
                    { field: 'link_url', title: '链接地址', width: '230' },
                    { field: 'system_type_name', title: '系统类型', width: '180' },
                    {
                        field: 'function_type', title: '功能类型', width: '100',
                        templet: function (d) {
                            for (var i = 0; i < self.Parameters.functionypeList.length; i++) {
                                if (self.Parameters.functionypeList[i].Value == d.function_type) {
                                    return self.Parameters.functionypeList[i].Text
                                }
                            }
                        }
                    },
                    //{ field: 'sort', title: '排序', width: '80', align: "center" },
                    { field: 'is_valid', title: '状态', width: 140, templet: '#switchValidTpl', align: "center" },
                    { title: '操作', toolbar: '#gridTool', width: '230', align: 'left' }
                ];

            var userInfo = GrdAdmin.getUserInfo();
            var treeTable = treeGrid.render({
                elem: '#menusList',
                headers: { "Authorization": userInfo != null ? "Bearer  " + JSON.parse(userInfo.token).auth_token : "" },//通过请求头来发送token，放弃了通过cookie的发送方式
                url: GrdAdmin.webURI + self.Parameters.listsUrl,
                cellMinWidth: 100,
                contentType: "application/json;charset=utf-8",
                height: "full-110",
                idField: 'id',//必須字段
                treeId: 'id',//树形id字段名称
                treeUpId: 'parent_id',//树形父parent_id字段名称
                treeShowName: 'name',//以树形式显示的字段
                isOpenDefault: true,//节点默认是展开还是折叠【默认展开】
                cheDisabled: true,
                isPage: true,
                cols: [title],
                onRadio: function (obj) {
                    self.Parameters.rowData = obj;
                    //单选事件
                    self.logicFunc.showHideBtn(obj);
                }
            });

            form.render();

        },
        //绑定事件
        bindEvent: function () {

            //查询
            $("#funBtnSearch").on("click", function () {
                self.logicFunc.loadListInfo();
            });

            //新增根节点
            $("#funBtnAddRoot").on("click", function () {
                self.Parameters.rowData = null;
                self.logicFunc.addInfo();
            });

            //上移
            $("#funBtnTop").on("click", function () {
                self.logicFunc.move(1);
            });

            //下移
            $("#funBtnBottom").on("click", function () {
                self.logicFunc.move(2);
            });

            //监听(列表操作)
            treeGrid.on('tool(menusList)', function (obj) {
                var data = obj.data;
                self.Parameters.rowData = data;
                //新增子节点
                if (obj.event === 'funBtnAdd') {
                    self.logicFunc.addInfo();
                }
                //修改
                else if (obj.event === 'funBtnEdit') {
                    self.logicFunc.modifyInfo();
                }
                //删除
                else if (obj.event === 'funBtnRemove') {
                    self.logicFunc.removeInfo();
                }
            });

            //监听启用/停用操作
            form.on('switch(funBtnValid)', function (obj) {
                self.logicFunc.forbiddenInfo(this.value);
                //layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
            });

             //对于单选框按钮点击行的选中功能：
            $(document).on("click", ".layui-table-body table.layui-table tbody tr", function () {
                /*当单击表格行时,把单选按钮设为选中状态*/
                var tableDiv;
                var index = $(this).attr('data-index');
                var tableBox = $(this).parents('.layui-table-box');
                //存在固定列
                if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length > 0) {
                    tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
                } else {
                    tableDiv = tableBox.find(".layui-table-body.layui-table-main");
                }
                var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.layui-table-cell div.layui-form-radio I");
                if (checkCell.length > 0) {
                    checkCell.click();
                }
            });
            //对td的单击事件进行拦截停止，防止事件冒泡再次触发上述的单击事件  将此代码在页面初始化后执行一次即可以。
            $(document).on("click", "td div.layui-table-cell div.layui-form-radio", function (e) {
                e.stopPropagation();
            });
        },
        //逻辑方法
        logicFunc: {

            //获取系统类型列表信息
            loadSystemTypeList: function (func) {
                GrdAdmin.ajaxRequest({
                    url: self.Parameters.systemTypeListUrl,
                    data: {},
                    type: GrdAdmin.ajaxGet,
                    success: function (result) {
                        if (result.Code == 1000) {
                            $("#system_type").empty();
                            self.Parameters.systemTypeList = result.Data;
                            for (var i = 0; i < result.Data.length; i++) {
                                $("#system_type").append("<option value=" + result.Data[i].Value + ">" + result.Data[i].Text + "</option>");
                            }
                        }
                        if (func) {
                            func();
                        }
                    }
                });
            },

            //获取功能类型列表信息
            loadFunctionTypeList: function (func) {
                GrdAdmin.ajaxRequest({
                    url: self.Parameters.functionTypeListUrl,
                    data: {},
                    type: GrdAdmin.ajaxGet,
                    success: function (result) {
                        if (result.Code == 1000) {
                            self.Parameters.functionypeList = result.Data;
                        }
                        if (func) {
                            func();
                        }
                    }
                });
            },

            ///获取数据
            loadListInfo: function () {
                treeGrid.reload("menusList", {
                    page: {
                        curr: 1
                    },
                    where: {
                        parameters: {
                            name: $("#func_name").val(),
                            system_type: $("#system_type").val()
                        }
                    }
                });
            },

            //增加信息
            addInfo: function () {
                var title = "增加根节点信息";
                var url = self.Parameters.addUrl;
                if (self.Parameters.rowData != undefined
                    && self.Parameters.rowData != null) {

                     //存储界面传递参数
                    var data = {
                        parent_id: self.Parameters.rowData.id
                    };
                    GrdAdmin.setUrlParameters(data);
                    title = "增加子节点信息";
                    url = self.Parameters.addUrl;
                }
                var index = layui.layer.open({
                    title: title,
                    type: 2,
                    resize: false,
                    area: ['550px', '530px'],
                    content: url,
                    end: function () {
                        $(window).unbind("resize");
                        self.Parameters.rowData = null;
                    }
                });
            },

            //修改信息
            modifyInfo: function () {

                if (self.Parameters.rowData != undefined
                    && self.Parameters.rowData != null) {

                    GrdAdmin.setUrlParameters(self.Parameters.rowData);

                    var index = layui.layer.open({
                        title: "修改菜单信息",
                        type: 2,
                        resize: false,
                        area: ['550px', '530px'],
                        content: self.Parameters.modifyUrl,
                        end: function () {
                            $(window).unbind("resize");
                            self.Parameters.rowData = null;
                        }
                    });
                }
            },

            //启用或停用
            forbiddenInfo: function (id) {
                GrdAdmin.ajaxRequest({
                    url: self.Parameters.forbiddenUrl,
                    data: { id:id } ,
                    type: GrdAdmin.ajaxGet,
                    success: function (result) {
                        if (result.Code == 1000) {
                            GrdAdmin.msg(result.Msg, "成功", function () {
                                self.logicFunc.loadListInfo();
                            });
                        } else {
                            GrdAdmin.msg(result.Msg, "警告");
                        }
                    }
                });
            },

            //删除信息
            removeInfo: function () {
                if (self.Parameters.rowData != undefined
                    && self.Parameters.rowData != null) {

                    GrdAdmin.confirm("确定删除信息吗？", function () {
                        var ids = new Array();//创建一个数组
                        ids.push(self.Parameters.rowData.id);

                        GrdAdmin.ajaxRequest({
                            url: self.Parameters.removeUrl,
                            data: ids,
                            success: function (result) {
                                if (result.Code == 1000) {
                                    GrdAdmin.msg(result.Msg, "成功", function () {
                                        self.logicFunc.loadListInfo();
                                    });
                                } else {
                                    GrdAdmin.msg(result.Msg, "警告");
                                }
                            }
                        });
                    });
                }
            },

            //显示或隐藏移动按钮
            showHideBtn: function (obj) {
                if (obj.have_elder) {
                    $("#funBtnTop").show();
                }
                else {
                    $("#funBtnTop").hide();
                }
                if (obj.have_younger) {
                    $("#funBtnBottom").show();
                } else {
                    $("#funBtnBottom").hide();
                }
            },
            //移动操作 flag==1上移   flag==2下移
            move: function (flag) {
                if (self.Parameters.rowData != null) {
                    var json = {
                        flag: flag,
                        id: self.Parameters.rowData.id
                    };
                    GrdAdmin.ajaxRequest({
                        url: self.Parameters.moveSortUrl,
                        data: json,
                        success: function (result) {
                            if (result.Code == 1000) {
                                self.logicFunc.loadListInfo();
                            } else {
                                GrdAdmin.msg(result.Msg, "警告");
                            }
                        }
                    });
                } else {
                    GrdLayUI.msg("请选择操作行！", "警告");
                }
            },
        },
        //工具
        tools: {

        }
    };
    authorityMenusListLogic.init();
});
